<template>
  <a-layout :style="{width: '100%'}">
    <top-bar @shopcarItems="getShopCarItems"/>
    <a-layout-content :style="{padding: '0 50px', marginTop: '64px', minHeight: '620px'}">
      <a-row style="margin-top: 15px" justify="space-around">
        <a-col :span="4"></a-col>
        <a-col :span="16"><a-steps :items="items"/></a-col>
        <a-col :span="4"></a-col>
      </a-row>
      <a-row v-if="currentProcess==='preSubmit'" style="margin-top: 10px" justify="space-around">
        <!--订单表单-->
        <a-col style="margin-top: 20px; text-align: left" :span="18">
          <a-descriptions title="收货人信息">
            <a-descriptions-item>
              <a-select
                  v-model:value="receiveAddress"
                  show-search
                  placeholder="请选择收货地址"
                  style="width: 320px"
                  :options="addressOptions"
                  :filter-option="filterOption"
                  @change="handleChange"
              />
            </a-descriptions-item>
            <a-descriptions-item/>
            <a-descriptions-item/>
            <a-descriptions-item label="姓名">{{visibleAddress[0]}}</a-descriptions-item>
            <a-descriptions-item label="电话">{{visibleAddress[1]}}</a-descriptions-item>
            <a-descriptions-item label="地址">{{visibleAddress[2]}}</a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col style="margin-top: 20px; text-align: left" :span="18">
          <a-descriptions title="支付方式">
            <a-descriptions-item>在线支付</a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col style="margin-top: 20px; text-align: left" :span="16">
          <a-typography-title :level="4">商品清单</a-typography-title>
          <a-list item-layout="vertical" :data-source="product">
            <template #renderItem="{ item }">
              <a-list-item>
                <template #extra>
                  <img
                      width="130"
                      alt="logo"
                      :src="item.skuDefaultImg"
                  />
                </template>
                <a-list-item-meta
                    description="这里可以放介绍信息"
                >
                  <template #title>
                    <router-link :to="{path: '/product/info/baseAttrs', query: {skuId: item.skuId}}">
                      {{ item.skuName }}
                    </router-link>
                  </template>
                </a-list-item-meta>
                <a-descriptions>
                  <a-descriptions-item label="单价">￥ {{item.price}}</a-descriptions-item>
                  <a-descriptions-item label="数量">x{{item.count}}</a-descriptions-item>
                  <a-descriptions-item label="小计">
                    <a-typography-text strong>
                      ￥{{item.totalPrice}}
                    </a-typography-text>
                  </a-descriptions-item>
                  <a-descriptions-item><a-tag color="cyan" v-for="attr in item.saleAttrs">{{attr}}</a-tag></a-descriptions-item>
                  <a-descriptions-item v-if="item.hasStock === false"><a-tag color="warning">
                    <template #icon>
                      <exclamation-circle-outlined />
                    </template>无货</a-tag></a-descriptions-item>
                </a-descriptions>
              </a-list-item>
            </template>
          </a-list>
        </a-col>
        <a-col style="margin-top: 20px; text-align: left" :span="18">
          <a-card title="使用优惠卷/礼品卡/抵用">
            <a-card-grid style="width: 25%; text-align: center">Content</a-card-grid>
            <a-card-grid style="width: 25%; text-align: center" :hoverable="false">Content</a-card-grid>
            <a-card-grid style="width: 25%; text-align: center">Content</a-card-grid>
          </a-card>
        </a-col>
      </a-row>
      <a-result v-if="resultVisible === 'success'"
          status="success"
          title="购买成功!"
          sub-title="商品正在火速出库中，请等待收货使用！"
      >
        <template #extra>
          <a-button key="console" type="primary">再订一单</a-button>
          <a-button key="buy">再逛逛</a-button>
        </template>
      </a-result>

      <a-result v-if="resultVisible==='failed'"
          status="error"
          title="购买失败"
          sub-title="请重新提交订单"
      >
        <template #extra>
          <a-button key="console" type="primary">Go Console</a-button>
          <a-button key="buy">Buy Again</a-button>
        </template>
      </a-result>
    </a-layout-content>
    <a-layout-footer v-if="currentProcess==='preSubmit'" style="text-align: right">
      <a-typography-title :level="2">应付金额：{{payMoney}}￥</a-typography-title>
      <a-button :disabled="submitVisible" @click="submitOrder" size="large" type="primary" danger>提交订单</a-button>
    </a-layout-footer>
    <tail-bar/>
  </a-layout>

</template>

<script setup>
import TopBar from "@/components/common/TopBar.vue";
import TailBar from "@/components/common/TailBar.vue";
import {h, ref, onBeforeMount, watch} from 'vue';
import {v4} from 'uuid'
import {
  LoadingOutlined,
  SmileOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue';
import router from "@/router";
import request from "@/utils/request";
import {message} from "ant-design-vue";


let product = ref([])  //购买的商品
let payMoney = ref(0.0)
let receiveAddress = ref(undefined) //选择的收货地址
const addressOptions = ref([])  //可选的收货地址
let visibleAddress = ref([])
let submitVisible  = ref(false)
const orderToken = v4()
let currentProcess = ref('')
let resultVisible = ref('')

let items = [];

/**
 * 子组件 topBar 传递过来的商品数据
 * @param data_temp
 */
const getShopCarItems = (data_temp) => {
}

const getReceiveAddress=()=> {
  request({
    url: '/auth/user/get-userInfo',
    method: 'get'
  }).then(res => {
    if(res.code === 0){
      res.data.receiveAddresses.forEach(item => {
        let str = item.name + '_' + item.phone+'_'+ item.province+'-'+item.city+'-'+item.region+'-'+item.detailAddress
        item['value'] = str
        item['label'] = str
        addressOptions.value.push(item)
        if(item.defaultStatus === 1){
          receiveAddress.value = item.value
          visibleAddress.value = item.value.split('_')
        }
      })
    }else {
      console.log('服务端获取session异常', res.msg)
      message.error(res.msg)
    }
  }).catch(err => {
    console.log('获取session异常', err.message)
  })
}

/**
 * 获取订单的商品数据
 * @param skuIdMetas 数组 [{skuId, count}]
 */
const getProduct = (skuIdMetas)=> {
  let skuIdCountMap = new Map() // {key:skuId, value: count}
  let skuIds = []
  skuIdMetas.forEach(meta => {
    skuIds.push(meta.skuId)
    skuIdCountMap.set(meta.skuId, meta.count)
  })
  request({
    url: '/auth/user/order/get-skus',
    method: 'post',
    data: skuIds
  }).then(res => {
    console.log(res)
    if(res.code === 0){
      payMoney.value = 0
      res.data.forEach(item => {
        item['count'] = skuIdCountMap.get(item.skuId);
        item['totalPrice'] = item.count * item.price
        if(item.hasStock){
          payMoney.value += item.totalPrice
        }
        product.value.push(item)
      })
    } else {
      message.info(res.msg)
    }
  }).catch(err => {
    console.log(`获取商品信息异常${err.message}`)
    message.error(`获取商品信息异常${err.message}`)
  })
}

const handleChange = value => {
  console.log(`selected ${value}`);
  visibleAddress.value = value.split('_')
};
const filterOption = (input, option) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const submitOrder = () => {
  let address = visibleAddress.value[2].split('-')
  let items = []
  product.value.forEach(p => {
    //过滤掉无货的商量
    if(p.hasStock){
      items.push({skuId: p.skuId, count: p.count})
    }
  })
  let postData = {
    "orderToken": orderToken,
    "payType": 1,
    "sourceType": 0,
    "receiverName": visibleAddress.value[0],
    "receiverPhone": visibleAddress.value[1],
    "receiverProvince":address[0],
    "receiverCity": address[1],
    "receiverRegion": address[2],
    "receiverDetailAddress": address[3],
    "orderItems":items
  }
  if(items.length > 0){
    submitVisible.value = true
    //提交订单
    request({
      url : '/auth/user/order/add-newOrder',
      method: 'post',
      data: request.adornData(postData, false)
    }).then(res => {
      if(res.code === 0){
        message.success(res.msg)
        router.push({
          name: 'cashier-page',
          params: {orderId: res.data.orderId, orderSn: res.data.orderSn}
        })
        console.log(res)
      } else {
        message.info(`提交订单失败-${res.msg}`)
      }
    }).catch(err => {
      console.log(err.message)
      message.error(`提交订单异常${err.message}`)
    }).finally(_=>{
      submitVisible.value = false
    })
  } else {
    message.info('请重新选购，当前购买商品无货')
  }
}

const queryTrade= ()=> {
  console.log('请求订单状态', currentProcess.value)
  if (currentProcess.value === 'submitted' && typeof router.currentRoute.value.query.orderSn !== "undefined") {
    let orderSn = router.currentRoute.value.query.orderSn
    request({
      url: '/third-party/alipay.trade.query',
      method: 'get',
      params: {orderSn}
    }).then(res=>{
      if (res.code === 0) {
       let status = JSON.parse(res.data).alipay_trade_query_response.trade_status
        if (status === 'TRADE_SUCCESS' || status === 'TRADE_FINISHED') {
          resultVisible.value = 'success'
        } else {
          resultVisible.value = 'failed'
        }
      } else {
        message.info(res.msg)
      }
    }).catch(err=>{
      message.error(err.message)
    })
  }
}

onBeforeMount(_=>{
  getReceiveAddress()
  let skuIdMetas = []
  currentProcess.value = router.currentRoute.value.params.status
  router.currentRoute.value.params.skuIds.split(',').forEach(item => {
    let str = item.split(':')
    skuIdMetas.push({skuId: parseInt(str[0]), count: parseInt(str[1])})
  })
  queryTrade()
  items.push({
        title: '选购',
        status: 'finish'
      },
      {
        title: '填写订单',
        status: currentProcess.value === 'preSubmit' ?'process':'finish',
      },
      {
        title: '订单结果',
        status: currentProcess.value === 'submitted' ? 'finish' : 'wait',
        icon: h(SmileOutlined),
      },)
  getProduct(skuIdMetas);

})
</script>